package com.gdzl_hadoop.common;

import ch.ethz.ssh2.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class WinToLinux {

	private String result = "null";
	private String hostname;
	private String username;
	private String password;

	public String getResult()
	{
		return result;
	}

	public void setResult(String result)
	{
		this.result = result;
	}

	public WinToLinux(String hostname, String username , String password)
	{
		this.hostname = hostname;
		this.username = username;
		this.password = password;
	}

	public InputStream executeCommand(String command) {
		// TODO Auto-generated method stub
		// String hostname = "192.168.10.147";
		//     String username = "hadoop";
		//    String password = "pass@word1";
		InputStream inputStream= null;
		StringBuilder result =new StringBuilder() ;
		try
		{
			Connection conn = new Connection(hostname);
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);
			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
			else
			{
				System.out.println("Connection Success");
			}
			Session sess = conn.openSession();

			//"cat /home/hadoop/test_mahout_data/MYtestaaaaa.txt"
			sess.execCommand("cat /home/hadoop/cp_data.txt");
			//sess.execCommand("echo 'EOF1'");

			inputStream=sess.getStdout();
			InputStream stdout =new StreamGobbler(sess.getStdout());


			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

			/*while (true)
			{
				String line = br.readLine();
				if (line.equals("Count: 37"))
					break;
				System.out.println(line);
				result.append(line);
			}

			System.out.println("ExitCode: " + sess.getExitStatus());
			result.append("ExitCode: " + sess.getExitStatus());*/

			sess.close();

			conn.close();


		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			result.append(System.err);
			System.exit(2);
		}

		this.setResult(result.toString());
		return inputStream;


	}


}
